package com.doubleview.demo

import groovy.io.FileType
import groovy.io.FileVisitResult


/**
 * @author huchengchao <huchengchao@kuaishou.com>
 * Created on 2021-11-20
 */
def baseDir = '.'
new File(baseDir, 'gc.log').eachLine { line ->
    println line
}

new File(baseDir, 'gc.log').eachLine { line, nb ->
    println "Line $nb: $line"
}

def count = 0, MAXSIZE = 3
new File(baseDir, "gc.log").withReader { reader ->
    while (reader.readLine()) {
        if (++count > MAXSIZE) {
            throw new RuntimeException('Haiku should only have 3 verses')
        }
    }
}

//收集文本文件的每一行到一个列表中
def list = new File(baseDir, 'haiku.txt').collect { it }
//用as操作符来讲文件内容转为String数组
def array = new File(baseDir, 'haiku.txt') as String[]

//获得一个文件的内容到一个byte[]
def file = new File("")
byte[] contents = file.bytes

// 从一个文件获得一个InputStream
def is = new File(baseDir, 'haiku.txt').newInputStream()
// do something ...
is.close()

new File(baseDir, 'haiku.txt').withInputStream { stream ->
    // do something ...
}

//======================写文件==================
new File(baseDir, 'haiku.txt').withWriter('utf-8') { writer ->
    writer.writeLine 'Into the ancient pond'
    writer.writeLine 'A frog jumps'
    writer.writeLine 'Water’s sound!'
}

// 使用<< 操作符
new File(baseDir, 'haiku.txt') << '''Into the ancient pond
A frog jumps
Water’s sound!'''
//直接写入字节
file.bytes = [66, 22, 11]

// 直接处理输出流
def os = new File(baseDir, 'data.bin').newOutputStream()
// do something ...
os.close()


// ===================遍历文件数================
//在目录的每一个文件直行闭包代码
dir = new File("")
dir.eachFile { f ->
    println f.name
}

//在目录中符合匹配模式的文件直行闭包代码
dir.eachFileMatch(~/.*\.txt/) { f ->
    println f.name
}

//在指定目录递归查找，并在每一个文件和目录直行闭包代码
dir.eachFileRecurse { f ->
    println f.name
}

//在指定目录递归查找，并在每一个文件直行闭包代码
dir.eachFileRecurse(FileType.FILES) { f ->
    println file.name
}

dir.traverse { f ->
    if (f.directory && f.name == 'bin') {
        //如果当前file是一个目录或者它的名字是 bin ，则停止遍历
        FileVisitResult.TERMINATE
    } else {
        //打印文件名并继续遍历
        println f.name
        FileVisitResult.CONTINUE
    }

}
